package cn.kwq.pcsystem.utils;

import cn.kwq.pcsystem.concurrent.ConcurrentJobThreadUtils;
import cn.kwq.pcsystem.concurrent.JobThreadConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * Created with IntelliJ IDEA.
 * 多线程工具类
 * @Author: kwq
 * @Date: 2023/03/06/2:13
 * @Description:
 */
@Slf4j
public class ConcurrentUtil {

    /**
     * 带重试的异步工作线程
     * @param config  配置对象，time<=0时不规定执行时间
     * @param executorService 线程池对象
     */
    public static void doJob(JobThreadConfig config, ExecutorService executorService){
        try {
            ConcurrentJobThreadUtils.doJob(config,executorService);
            if (!executorService.awaitTermination(config.getTime(), TimeUnit.SECONDS)&&config.getTime()>0){
                executorService.shutdownNow();
                log.error("{}任务 {} 秒内未完成，关闭任务",config.getJobName(),config.getTime());
            }
        }catch (Exception e){
            log.error("任务发生错误");
            e.printStackTrace();
        }

    }
    @Deprecated
    public static void doJob(Runnable job,ExecutorService executorService){
        try {
            JobThreadConfig config=new JobThreadConfig();
            config.setJob(job).setJobName("未命名任务"+job.hashCode()).setDelay(0).setTryTimes(3);
            ConcurrentJobThreadUtils.doJob(config,executorService);
        }catch (Exception e){
            log.error("任务发生错误");
            e.printStackTrace();
        }
    }

    /**
     * 获取一个工具类对象
     * @return 工具类对象
     */
    public static ConcurrentUtil getUtils(){
        return new ConcurrentUtil();
    }

    /**
     * 用默认设置线程池执行异步工作
     * @param consumer 异步工作lambda方法
     * @param t 消费对象
     * @param <T> 消费对象类型
     */
    @Async("MyExecutorService")
    public <T> void easyJob(Consumer<T> consumer, T t){
        consumer.accept(t);
    }


}
